
// 142.环形链表II
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        // 先判断链表是否带环
        ListNode* slow = head , *fast = head;
        while(fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast) break;
        }
        if(fast == nullptr || fast->next == nullptr) return nullptr;
        // 此时slow就是两个指针相交的位置
        ListNode* cur = head;
        while(cur != slow)
        {
            cur = cur->next;
            slow = slow->next;
        }
        return cur;
    }
};